package com.baimsg.poc

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import com.baimsg.poc.databinding.ActivityMainBinding
import com.baimsg.poc.service.PocWidgetService
import com.baimsg.poc.utils.updateWidget

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        binding = ActivityMainBinding.inflate(layoutInflater)

        if (::binding.isInitialized) {

            setContentView(binding.root)

            with(binding) {

                tvUpdateIdle.setOnClickListener {
                    updateService(true)
                    updateWidget(this@MainActivity, 1)
                    toast("已更新")
                }

                tvUpdateOffline.setOnClickListener {
                    updateService(true)
                    updateWidget(this@MainActivity, 3)
                    toast("已更新")
                }

                tvUpdateTalk.setOnClickListener {
                    updateService(true)
                    updateWidget(this@MainActivity, 2)
                    toast("已更新")
                }

                tvStartService.setOnClickListener {
                    updateService(false)
                }

                tvStopService.setOnClickListener {
                    updateService(true)
                }
            }
        }
    }

    private fun updateService(stop: Boolean) {
        if (PocWidgetService.running && !stop) {
            return
        }
        if (!PocWidgetService.running && stop) {
            return
        }
        val intent = Intent(this, PocWidgetService::class.java)
        if (stop) {
            stopService(intent)
        } else {
            startService(intent)
        }
    }

    private fun toast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}